const express = require('express')
const {queryDB,queryDBPromise} = require('../db/utildb.js')
const userRouter = express.Router() // 路由对象

//创建一个路由
/**
 *   username:'admin'
 *   password:'123'
 *   age:18,
 *   sex:'男'
 */
userRouter.post('/register', (req, res) => {
	// 接收参数
	const username = req.body.username
	const password = req.body.password
	const age = req.body.age
	const sex = req.body.sex

	// 保存用户到数据库
	const sql = `INSERT INTO users(username,password,age,sex) VALUES ("${username}","${password}",${age},"${sex}")`
	queryDB(sql, function (results) {
		console.log(results)

		res.send({
			code: 1,
			message: '注册成功!',
		})
	})
})

/**
 * 登录
 */
userRouter.get('/login', (req, res) => {
	const username = req.query.username
	const password = req.query.password

	const sql = `SELECT id,username,password,age,sex FROM users WHERE username="${username}" AND password="${password}"`
	
	queryDBPromise(sql).then(results=>{
		if (results.length >= 1) {
			res.send({
				code: 1,
				message: '登录成功',
			})
		} else {
			res.send({
				code: -1,
				message: '用户名或者密码出错！',
			})
		}
	})
	
})

module.exports = {
	userRouter,
}
